package com.iot.iotplus.service.impl;

import com.iot.iotplus.base.Result;
import com.iot.iotplus.entity.Message;
import com.iot.iotplus.mapper.MessageMapper;
import com.iot.iotplus.mapper.MqttUserMapper;
import com.iot.iotplus.service.MessageService;
import com.iot.iotplus.utils.MsgUtil;
import com.iot.iotplus.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MqttUserMapper mqttUserMapper;
    @Override
    public Result<?> saveMessage(String message) {
        try {
            Optional.of(message);
        }catch (NullPointerException e){
            return ResultUtil.failed();
        }
        Message m = MsgUtil.getMessage(message);
        int insert = messageMapper.insert(m);

        return ResultUtil.success(insert);
    }

    @Override
    public String getMqttUser(String tenantId) {
        if (tenantId.isEmpty()) return null;
        String userName = mqttUserMapper.selectByTenantIdMqttUserName(tenantId);
        if (userName == null) return null;
        return userName;
    }

    @Override
    public Result<?> getAirTemperatures(String id) {
        if (id.isEmpty())
            return ResultUtil.failed();
        List<Float> list = messageMapper.getAirTemperatures(id);
        if (list.isEmpty())
            return ResultUtil.failed();
        return ResultUtil.success(list);
    }

    @Override
    public Result<?> getAirHumidity(String id) {
        if (id.isEmpty())
            return ResultUtil.failed();
        List<Float> list = messageMapper.getAirHumidity(id);
        if (list.isEmpty())
            return ResultUtil.failed();
        return ResultUtil.success(list);
    }


}
